package com.winit.openapi.ece.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.ContractService;
import com.winit.erp.spi.bpartner.command.ContractCommand;
import com.winit.oms.spi.ece.EceDeliveryService;
import com.winit.oms.spi.ece.command.EceDeliveryCommand;
import com.winit.oms.spi.ece.vo.EceDeliveryResult;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;

/**
 * 兼容进口一期   发货通知单相关
 * 
 * @version <pre>
 * Author	  Version		Date		Changes
 * dinghua.an	1.0  		2015年9月6日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/isp/dispatchNoticeOrder")
public class DispatchNoticeController extends BaseController {

    @Resource
    EceDeliveryService      eceDeliveryService;
    @Resource
    private ContractService agreementService;

    /**
     * 创建发货通知单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/create")
    public String create(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 效验用户是否是isp业务用户
        checkIspRight();
        Object obj = requestMsg.getData();
        List<String> list = new ArrayList<String>();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            ValidateUtil.validList(json, "orderNo", true);
            JSONArray orderNoList = json.getJSONArray("orderNo");
            for (Object object : orderNoList) {
                JSONObject orderNoObj = (JSONObject) object;
                ValidateUtil.validNotNull(orderNoObj, "documentNo");
                ValidateUtil.validMaxLength(orderNoObj, "documentNo", 60);
                list.add(orderNoObj.getString("documentNo").trim());
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        // 调用接口确认发货
        EceDeliveryCommand command = new EceDeliveryCommand();
        command.setOrderNoList(list);
        EceDeliveryResult result = new EceDeliveryResult();
        result = eceDeliveryService.confirm(command);

        if (null != result) {
            // 返回操作结果
            Map<String, Object> data = new HashMap<String, Object>();
            if (result.getSuccessCount() > 0) {
                data.put("dispatchNoticeOrderNo", createDnOrderNo());
            }
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.CONFIRM_DELIVERY_FAILD);
        }

        return SUCCESS;
    }

    /**
     * 提交发货通知单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/submit")
    public String submit(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 效验用户是否是isp业务用户
        checkIspRight();
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            ValidateUtil.validNotNull(json, "dispatchNoticeOrderNo");
            ValidateUtil.validMaxLength(json, "dispatchNoticeOrderNo", 32);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    /**
     * 校验用户是不是isp用户
     */
    private void checkIspRight() {
        ContractCommand command = new ContractCommand();
        command.setBusiType("ISP");
        command.setBpartnerId(Long.parseLong(CommandContext.getContext().getUserId()));
        boolean rightStatus = agreementService.isOpenContract(command);

        if (!rightStatus) {
            throw new ApiException(ErrorCode.USERNAME_ISNOT_ISP_USER);
        }
    }

    /**
     * 随机生成发货通知单号
     * 
     * @return
     */
    private String createDnOrderNo() {
        int max = 9;
        int min = 1;
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        String dispatchNoticeOrderNo = "IF15" + new Date().getTime() + s + "CN";
        return dispatchNoticeOrderNo;
    }
}
